{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c23d6334",
   "metadata": {},
   "source": [
    "* 百度AI实践\n",
    "* 自然语言处理文本信息（实践）\n",
    "* 自然语言生成文本信息（实践）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fcbe3fb7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"text\":\"我喜欢吃西瓜\",\"items\":[{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"我\",\"loc_details\":[],\"basic_words\":[\"我\"],\"byte_offset\":0,\"byte_length\":2,\"pos\":\"\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"喜欢\",\"loc_details\":[],\"basic_words\":[\"喜欢\"],\"byte_offset\":2,\"byte_length\":4,\"pos\":\"v\"},{\"uri\":\"\",\"formal\":\"\",\"ne\":\"\",\"item\":\"吃西瓜\",\"loc_details\":[],\"basic_words\":[\"吃\",\"西瓜\"],\"byte_offset\":6,\"byte_length\":6,\"pos\":\"vn\"}],\"log_id\":1650336626389938625}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "API_KEY = \"kkRLfRq26u6Qpur0ZIb3sFTA\"\n",
    "SECRET_KEY = \"qBLh1AOY8BcMUGjfhpE8VoCaclOSioyV\"\n",
    "\n",
    "def main():\n",
    "        \n",
    "    url = \"https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8&access_token=\" + get_access_token()\n",
    "    \n",
    "    payload = json.dumps({\n",
    "        \"text\": \"我喜欢吃西瓜\"\n",
    "    })\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Accept': 'application/json'\n",
    "    }\n",
    "    \n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "    \n",
    "    print(response.text)\n",
    "    \n",
    "\n",
    "def get_access_token():\n",
    "    \"\"\"\n",
    "    使用 AK，SK 生成鉴权签名（Access Token）\n",
    "    :return: access_token，或是None(如果错误)\n",
    "    \"\"\"\n",
    "    url = \"https://aip.baidubce.com/oauth/2.0/token\"\n",
    "    params = {\"grant_type\": \"client_credentials\", \"client_id\": API_KEY, \"client_secret\": SECRET_KEY}\n",
    "    return str(requests.post(url, params=params).json().get(\"access_token\"))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d532fb0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
